'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 离开战斗
 * @author sundbcn@gmail.com (sun debing)
 */

var _ = require('lodash');
var async = require('async');
var moment = require('moment');
var Code = require('../../../../consts/code');
var moduleType = require('../../../../consts/moduleType');
var operationType = require('../../../../consts/operationType');
var battleRecordModel = require('../../../../models/battleRecordModel');
var unionGroupModel = require('../../../../models/unionGroupModel');
var heroConf = require('../../../../config/heroConf');
var battleConf = require('../../../../config/battleConf');
var fightRewardUtil = require('../../../../util/fightRewardUtil');
var constantUtil = require('../../../../util/constantUtil');
var roleService = require('../../../../services/roleService');
var battleService = require('../../../../services/battleService');
var PlayerManager = require('../../../../libs/playerManager');
var rewardService = require('../../../../services/rewardService');
var pvpConf = require('../../../../config/pvpConf.js');
var marqueeModel = require('../../../../models/marqueeModel.js');
var marqueeConf = require('../../../../config/marqueeConf');
var vipConf = require('../../../../config/vipConf.js');
var taskService = require('../../../../services/taskService.js');
var pvpService = require('../../../../services/pvpService.js');
var rivalService = require('../../../../services/rivalService');

// 掠夺
var BATTLE_HARRY = 1;
// 复仇
var BATTLE_REVENGE = 2;

module.exports = function (msg, session, next) {
    var role_id = session.uid;
    var record_id = msg.record_id;
    var damage_build_list = msg.damage_build_list || [];
    var data = msg.data || {};
    if (!record_id) {
        return next(null, {
            code: Code.PARAM_ERROR
        });
    }

    var atk_player_manager = new PlayerManager(role_id);
    var def_player_manager;

    var battle_record_model;
    var atk_role_model;
    var def_role_model;
    var atk_battle_model;

    var add_train_exp_soldier_list;
    var add_cup = 0;
    var add_dragon_gold = 0;
    var extra_gold = 0;
    var add_prosperous = 0;
    var add_honor = 0;
    var first_reward = [];
    var def_union_model = null;
    var star = 0;

    async.waterfall(
        [
            function (cb) {
                battleRecordModel.getRecordByAtkRoleId(role_id, record_id, cb);
            },
            function (model, cb) {
                battle_record_model = model;

                if (!battle_record_model) {
                    return next(null, {
                        code: Code.BATTLE_RECORD_NOT_EXIST
                    });
                }

                if (!!battle_record_model.isEnd()) {
                    return next(null, {
                        code: Code.COPY_HAVE_PASS
                    });
                }
                cb();
            },
            function (cb) {
                atk_player_manager.refreshData(cb);
            },
            function (cb) {
                atk_player_manager.getModel(
                    ['role', 'pvp', 'battle', 'bag', 'soldier', 'skill', 'build', 'task', 'daily_task', 'achieve', 'sevenDayActivity', 'accrued'],
                    cb);
            },
            function (cb) {
                atk_role_model = atk_player_manager.role;
                atk_battle_model = atk_player_manager.battle;

                var pvp_gold_reward = heroConf.getHeroLvConf(atk_role_model.getLv()).pvp_gold_reward;
                var gold_ratio = battleConf.getNobleConf(atk_battle_model.getNoble()).gold_ratio;

                // 掠夺增加固定金币奖励
                extra_gold = Math.round(pvp_gold_reward * gold_ratio) + pvp_gold_reward;
                cb();
            },
            function (cb) {
                def_player_manager = new PlayerManager(battle_record_model.def_role_id);
                def_player_manager.refreshData(cb);
            },
            function (cb) {
                def_player_manager.getModel(
                    ['role', 'pvp', 'battle', 'bag', 'soldier', 'skill', 'build', 'task', 'daily_task', 'achieve', 'tech', 'sevenDayActivity', 'accrued'],
                    cb);
            },
            function (cb) {
                var union_id = def_player_manager.role.union_id;
                if (union_id !== 0) {
                    unionGroupModel.getById(union_id, function (err, model) {
                        def_union_model = model;
                        cb();
                    });
                } else {
                    cb();
                }
            },
            // jshint maxstatements:100
            function (cb) {
                def_role_model = def_player_manager.role;

                var atk_pvp_model = atk_player_manager.pvp;
                var def_pvp_model = def_player_manager.pvp;

                // 摧毁建筑比例
                var damage_progress = fightRewardUtil.getDamageProgress(battle_record_model, damage_build_list);

                // 打到的资源
                var vip_value = (vipConf.getConf(atk_role_model.getVip()).add_pvp_reward) / 100;
                var add_gold = Math.ceil((battle_record_model.getDefTotalGold() * damage_progress / 100) * (1 + vip_value));
                var add_food = Math.ceil((battle_record_model.getDefTotalFood() * damage_progress / 100) * (1 + vip_value));

                // 毁坏建筑能拿到的经验
                var add_exp = heroConf.getHeroPvpExp(atk_role_model.getLv());

                // 副本的星级
                star = _getStar(battle_record_model, damage_build_list);

                var att_main_power = atk_player_manager.role.main_power;
                var def_main_power = def_player_manager.role.main_power;

                var pvp_star_conf = null;
                var is_protect = def_player_manager.role.isProtect();

                // 奖杯数
                var cup = 1;
                // cup = _calcCup(att_main_power, def_main_power);
                if (star > 0) {
                    // 获胜

                    // 增加军功宝箱星数
                    atk_pvp_model.addHonorBoxStar(star);

                    // 获胜，增加星数和资源，限制10次
                    if (atk_role_model.decHarryCnt()) {
                        first_reward = _addCup(atk_player_manager, cup);
                        add_cup = cup;

                        add_gold = roleService.addGoldLimit(atk_player_manager, moduleType.MDL_PVP, operationType.OPR_PVP_FIGHT, add_gold);
                        add_food = roleService.addFoodLimit(atk_player_manager, moduleType.MDL_PVP, operationType.OPR_PVP_FIGHT, add_food);
                        roleService.addExp(atk_player_manager, add_exp);
                    } else {
                        add_gold = 0;
                        add_food = 0;
                        add_exp = 0;
                    }

                    pvp_star_conf = pvpConf.getPvpStarConf(star);
                    if (!pvp_star_conf) {
                        return next(null, {
                            code: Code.BATTLE_INVALID_PVP_STAR
                        });
                    }

                    // // 繁荣度
                    // add_prosperous = pvp_star_conf.prosperous;
                    // roleService.addProsperous(atk_player_manager, add_prosperous);

                    // 军功
                    add_honor = pvp_star_conf.honor;
                    roleService.addHonor(atk_player_manager, add_honor);

                    // 战斗胜利，将防守方从进攻方的黑名单列表中移除
                    atk_pvp_model.removeFromBlackList(def_player_manager.getRoleId());

                    if (!is_protect) {
                        // 增加保护时间
                        var add_protect_time = constantUtil.value('protect_time');
                        roleService.addProtectTime(def_player_manager, add_protect_time);

                        // 官阶保护(高打低不降，同级打男爵以下不降)
                        var atk_noble = atk_role_model.noble;
                        var def_noble = def_role_model.noble;
                        var protect_position_lvl = constantUtil.value('protect_position_lvl');
                        // jshint maxdepth: 5
                        if (atk_noble < def_noble || (atk_noble == def_noble && def_noble <= protect_position_lvl)) {
                            // 防守失败降星，限制10次
                            if (def_role_model.decLessHarryCnt()) {
                                _subCup(def_player_manager, 1);
                            }
                        }

                        // 防守方扣资源
                        var def_role = def_player_manager.role;
                        var def_build = def_player_manager.build;
                        var def_tech = def_player_manager.tech;
                        var harry_res = pvpService.getHarryRes(def_role, def_build, def_tech, def_union_model);
                        var vip_reduce = vipConf.getConf(def_role.getVip()).reduce_robbed_resource;
                        var sub_gold = harry_res.gold * damage_progress / 100 * (100 - vip_reduce) / 100;
                        var sub_food = harry_res.food * damage_progress / 100 * (100 - vip_reduce) / 100;

                        roleService.subGold(def_player_manager, moduleType.MDL_PVP, operationType.OPR_PVP_DEF_FAILED, sub_gold);
                        roleService.subFood(def_player_manager, moduleType.MDL_PVP, operationType.OPR_PVP_DEF_FAILED, sub_food);

                        // // 繁荣度
                        // roleService.subProsperous(def_player_manager, add_prosperous);

                        // 军功
                        roleService.subHonor(def_player_manager, add_honor);

                        if (battle_record_model.getBattleType() == BATTLE_HARRY) {
                            // 战斗胜利，将进攻方添加到防守方的黑名单列表中(复仇则不加入对方黑名单中)
                            def_pvp_model.addToBlackList(atk_player_manager.getRoleId());
                        }
                    }

                    // 掠夺胜利加入统计   217
                    taskService.addBattleSuccess(atk_player_manager);
                } else {
                    // 失败
                    add_cup = 0;

                    if (atk_role_model.decHarryCnt()) {
                        var loser_ratio = constantUtil.value('pvp_loser_ratio');
                        add_gold = Math.floor(add_gold * loser_ratio / 100);
                        add_food = Math.floor(add_food * loser_ratio / 100);
                        add_exp = Math.floor(add_exp * loser_ratio / 100);

                        add_gold = roleService.addGoldLimit(atk_player_manager, moduleType.MDL_PVP, operationType.OPR_PVP_FIGHT, add_gold);
                        add_food = roleService.addFoodLimit(atk_player_manager, moduleType.MDL_PVP, operationType.OPR_PVP_FIGHT, add_food);
                        roleService.addExp(atk_player_manager, add_exp);
                    } else {
                        add_gold = 0;
                        add_food = 0;
                        add_exp = 0;
                    }

                    // 军功(进攻方给防守方1星对应军功)
                    pvp_star_conf = pvpConf.getPvpStarConf(1);
                    if (!pvp_star_conf) {
                        return next(null, {
                            code: Code.BATTLE_INVALID_PVP_STAR
                        });
                    }

                    var sub_honor = pvp_star_conf.honor;
                    roleService.subHonor(atk_player_manager, sub_honor);
                    roleService.addHonor(def_player_manager, sub_honor);
                    add_honor = -sub_honor;
                }

                var lost_soldier_list = data.lost_soldier_list;
                if (!!lost_soldier_list) {
                    _.each(lost_soldier_list, function (soldier_item) {
                        atk_player_manager.soldier.subProductedSoldierNum(soldier_item.soldier_type, soldier_item.num);
                    });
                }

                // 增加龙币，限制10次
                if (atk_role_model.decHarryDragonCnt()) {
                    // 龙币固定值
                    add_dragon_gold = 1;
                    roleService.addDragonGold(atk_player_manager, moduleType.MDL_PVP, operationType.OPR_PVP_FIGHT, add_dragon_gold);
                }

                var task_model = atk_player_manager.task;

                // 获取掠夺次数 达到条件发送系统公告
                var battle_num_num = task_model.getStaticList(217).battle_success_num;

                if (battle_num_num === undefined) {
                    battle_num_num = 0;
                }

                // 发送走马灯条件判断
                var itme_conf = marqueeConf.getConf(5);
                var item_list = marqueeConf.getMsgConf(5);

                _.some(item_list, function (value) {
                    if (value.value == battle_num_num) {

                        // 加入走马灯信息到数据库
                        var str = value.format;
                        var reg = /name/;
                        var name_value = atk_role_model.getName();
                        var text1 = str.replace(reg, name_value);

                        var list = ({
                            sort_id: itme_conf.priority,
                            text: text1,
                            is_time: itme_conf.fixed_time,
                            times: itme_conf.times,
                            interval_time: itme_conf.time
                        });

                        marqueeModel.create(list, function (err, module) {

                        });
                        return true;
                    }
                });

                // 设置数据
                battle_record_model.setStar(star);
                battle_record_model.setCup(cup);
                battle_record_model.setEarnGold(add_gold);
                battle_record_model.setEarnFood(add_food);
                battle_record_model.setEarnExp(add_exp);

                cb();
            },
            function (cb) {
                if (star > 0 && battle_record_model.getBattleType() == BATTLE_HARRY) {
                    // 掠夺获胜，则更换对手
                    var pvp_model = atk_player_manager.pvp;
                    var def_role_id = battle_record_model.def_role_id;
                    console.log('---def_role_id:', def_role_id);
                    console.log('---player_list:', pvp_model.player_list);
                    var road_player = pvp_model.findByRoleId(def_role_id);
                    var road_id = road_player.road_id;
                    rivalService.getRandomRivalRoleId(pvp_model.role_id, pvp_model.getPlayerRoleIdList(), function (err, rival_role_id) {
                        pvp_model.removeRoadPlayer(road_player);
                        pvp_model.addRoadPlayer({
                            road_id: road_id,
                            role_id: rival_role_id
                        });
                        cb();
                    });
                } else {
                    cb();
                }
            },
            function (cb) {
                battleService.exitBattle(
                    atk_player_manager,
                    def_player_manager,
                    battle_record_model.getEarnGold(),
                    battle_record_model.getStar(),
                    battle_record_model.getCup()
                );
                cb();
            },
            function (cb) {
                atk_player_manager.save(cb);
            },
            function (cb) {
                def_player_manager.save(cb);
            },
            function (cb) {
                battle_record_model.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK,
                result: {
                    def_name: battle_record_model.getDefName(),
                    add_gold: battle_record_model.getEarnGold(),
                    add_food: battle_record_model.getEarnFood(),
                    add_exp: battle_record_model.getEarnExp(),
                    add_cup: add_cup,
                    add_dragon_gold: add_dragon_gold,
                    star: battle_record_model.getStar(),
                    add_prosperous: add_prosperous,
                    add_honor: add_honor,
                    progress: battle_record_model.getProgress(),
                    add_train_exp_soldier_list: add_train_exp_soldier_list,
                    reward_list: battle_record_model.getRewardList(),
                    first_reward: first_reward
                }
            });
        }
    );
};

/**
 * 获取星级
 * @param  {[type]} battle_record_model  [description]
 * @param  {[type]} damage_build_list [description]
 * @return {[type]}                    [description]
 */
var _getStar = function (battle_record_model, damage_build_list) {
    return fightRewardUtil.getStar(battle_record_model, damage_build_list);
};

var _getCup = function (star, atk_lv, def_lv) {
    return fightRewardUtil.getCup(star, atk_lv, def_lv);
};

/**
 * 获取已经销毁的建筑能获得的经验
 */
var _getDestroyBuildExp = function (battle_record_model, damage_build_list) {
    return fightRewardUtil.getDestroyBuildExp(battle_record_model, damage_build_list);
};

/**
 * 增加奖杯
 */
var _addCup = function (player_manager, cup_num) {
    var reward_list = [];
    var battle_model = player_manager.battle;
    var role_model = player_manager.role;
    var old_max_noble = battle_model.getMaxNoble();
    battle_model.addCup(cup_num);
    role_model.noble = battle_model.getNoble();
    var new_max_noble = battle_model.getMaxNoble();
    if (new_max_noble > old_max_noble) {
        reward_list = battleConf.getFirstPositionReward(role_model.getJob(), new_max_noble);
        rewardService.addRewardListToRole(player_manager, reward_list, moduleType.MDL_PVP, operationType.OPR_PVP_INC_MAX_NOBLE);

        // 发送走马灯条件判断
        var itme_conf = marqueeConf.getConf(1);
        var item_list = marqueeConf.getMsgConf(1);
        var cup_value = battle_model.getCup();
        _.some(item_list, function (value) {
            if (value.value == cup_value) {
                // 加入走马灯信息到数据库
                var str = value.format;
                var reg = /name/;
                var name_value1 = role_model.getName();
                var text = str.replace(reg, name_value1);
                var list = ({
                    sort_id: itme_conf.priority,
                    text: text,
                    is_time: itme_conf.fixed_time,
                    times: itme_conf.times,
                    create_time: moment().add(itme_conf.time, 's')
                });

                marqueeModel.create(list);

                // 加入发送信息记录
                battle_model.addMsg(cup_value);
                battle_model.save();
                return true;
            }
        });
        // 任务统计
        taskService.addPvpCupNum(player_manager, battle_model.getCup());
    }

    return reward_list;
};

/**
 * 减少奖杯
 */
var _subCup = function (player_manager, cup_num) {
    var battle_model = player_manager.battle;
    var role_model = player_manager.role;
    battle_model.subCup(cup_num);
    role_model.noble = battle_model.getNoble();
};

/**
 * 计算星数
 */
var _calcCup = function (win_main_power, fail_main_power) {
    var diff = (fail_main_power - win_main_power) / win_main_power * 100;
    if (diff < -20) {
        return 0;
    }
    if (diff < 20) {
        return 1;
    }
    return 2;
};
